<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Download, Refresh } from '@element-plus/icons-vue';
import { BillingService, type ReconciliationData, type BillingQueryParams } from '@/services/billingService';

/**
 * 此页面对应账单中心的 应收对账单
 */
// 查询条件
const queryForm = reactive({
  reconciliationNo: '', // 对账单号
  customer: '', // 客户
  status: '', // 状态
  startDate: '', // 开始日期
  endDate: '', // 结束日期
  shippingStation: '', // 发货站
  deliveryStation: '' // 到达站
});

// 表格数据
const tableData = ref<ReconciliationData[]>([]);
// 表格加载状态
const loading = ref(false);
// 表格选中的行
const selectedRows = ref<ReconciliationData[]>([]);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 状态选项
const statusOptions = [
  { value: 'unsettled', label: '未结算' },
  { value: 'settled', label: '已结算' }
];

// 站点选项
const stationOptions = [
  { value: 'shijiazhuang', label: '石家庄站' },
  { value: 'beijing', label: '北京站' },
  { value: 'tianjin', label: '天津站' },
  { value: 'shanghai', label: '上海站' },
  { value: 'guangzhou', label: '广州站' },
  { value: 'shenzhen', label: '深圳站' }
];

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    const params: BillingQueryParams = {
      customer: queryForm.customer,
      startDate: queryForm.startDate,
      endDate: queryForm.endDate,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    const result = await BillingService.getReconciliationList(params);
    
    if (result.success) {
      tableData.value = result.data;
      pagination.total = result.total;
    } else {
      ElMessage.error('获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQueryForm = () => {
  Object.keys(queryForm).forEach(key => {
    (queryForm as any)[key] = '';
  });
  handleSearch();
};

// 查询数据
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTableData();
};

// 处理表格选择变化
const handleSelectionChange = (rows: ReconciliationData[]) => {
  selectedRows.value = rows;
};

// 处理分页变化
const handlePageChange = (currentPage: number) => {
  pagination.currentPage = currentPage;
  fetchTableData();
};

// 处理每页条数变化
const handleSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.currentPage = 1;
  fetchTableData();
};

// 结算对账单
const handleSettle = async (row: ReconciliationData) => {
  try {
    await ElMessageBox.confirm(
      `确定要结算对账单 ${row.reconciliationNo} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const result = await BillingService.settleReconciliation(row.objectId!);
    
    if (result.success) {
      ElMessage.success('对账单结算成功');
      fetchTableData();
    } else {
      ElMessage.error('对账单结算失败');
    }
  } catch (error) {
    // 用户取消操作或其他错误
  }
};

// 查看明细
const handleDetail = (row: ReconciliationData) => {
  ElMessage.info(`查看对账单明细 ${row.reconciliationNo}`);
  // TODO: 这里应该跳转到对账单详情页面或弹出详情对话框
};

// 格式化日期
const formatDate = (date: Date | string): string => {
  if (!date) return '';
  const d = new Date(date);
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 创建对账单
const createReconciliation = () => {
  ElMessage.info('创建新对账单');
};

// 导出对账单
const exportReconciliation = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要导出的对账单');
    return;
  }
  
  ElMessage.success(`已导出${selectedRows.value.length}个对账单`);
};

// 页面加载时获取数据
onMounted(() => {
  fetchTableData();
});
</script>

<template>
  <div class="billing-reconciliation-view">
    <div class="page-header">
      <h2 class="page-title">应收对账单</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryForm">
        <!-- 第一行：客户、对账单号、状态、发货站 -->
        <div class="search-row first-row">
          <div class="form-group">
            <el-form-item label="对账单号">
              <el-input v-model="queryForm.reconciliationNo" placeholder="请输入对账单号" clearable></el-input>
            </el-form-item>
          </div>
          
          <div class="form-group">
            <el-form-item label="客户">
              <el-input v-model="queryForm.customer" placeholder="请输入客户名称" clearable></el-input>
            </el-form-item>
          </div>
          
          <div class="form-group">
            <el-form-item label="状态">
              <el-select v-model="queryForm.status" placeholder="请选择" clearable>
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-group">
            <el-form-item label="发货站">
              <el-select v-model="queryForm.shippingStation" placeholder="请选择" clearable>
                <el-option
                  v-for="item in stationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        
        <!-- 第二行：日期和按钮 -->
        <div class="search-row second-row">
          <div class="date-group">
            <div class="form-group">
              <el-form-item label="开始日期">
                <el-date-picker
                  v-model="queryForm.startDate"
                  type="date"
                  placeholder="选择开始日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                ></el-date-picker>
              </el-form-item>
            </div>
            
            <div class="form-group">
              <el-form-item label="结束日期">
                <el-date-picker
                  v-model="queryForm.endDate"
                  type="date"
                  placeholder="选择结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                ></el-date-picker>
              </el-form-item>
            </div>
          </div>
          
          <div class="button-group">
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button @click="resetQueryForm">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left">
        <el-button type="primary" :icon="Plus" @click="createReconciliation">新建对账单</el-button>
        <el-button :icon="Download" @click="exportReconciliation">导出</el-button>
        <el-button :icon="Refresh" @click="fetchTableData">刷新</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column prop="reconciliationNo" label="对账单号" width="120" fixed="left" />
      <el-table-column prop="customerName" label="客户" width="100" fixed="left" />
      <el-table-column prop="totalOrders" label="订单总数量" width="100" align="center" />
      <el-table-column prop="totalCargoQuantity" label="货物数量" width="100" align="center" />
      <el-table-column prop="totalCargoVolume" label="货物总体积(方)" width="120" align="center" />
      <el-table-column prop="totalCargoWeight" label="货物总重量(KG)" width="120" align="center" />
      <el-table-column prop="totalReceivable" label="应收总金额(元)" width="130">
        <template #default="scope">
          <span>￥{{ scope.row.totalReceivable }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="totalReceived" label="实收总金额(元)" width="130">
        <template #default="scope">
          <span>￥{{ scope.row.totalReceived }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="创建人" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="160">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="senderName" label="发货人" width="100" />
      <el-table-column prop="senderPhone" label="发货人电话" width="130" />
      <el-table-column prop="senderAddress" label="发货人地址" width="200" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100" fixed="right">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.status === 0 ? 'info' : 
              scope.row.status === 1 ? 'warning' : 
              scope.row.status === 2 ? 'primary' : 'success'
            "
            size="small"
          >
            {{ BillingService.getReconciliationBillStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            text
            @click="handleDetail(scope.row)"
          >
            明细
          </el-button>
          
          <el-button 
            v-if="scope.row.status === 2"
            type="success" 
            size="small" 
            text
            @click="handleSettle(scope.row)"
          >
            结算
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.billing-reconciliation-view {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.search-container {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.search-row {
  display: flex;
  margin-bottom: 16px;
}

.search-row.first-row {
  justify-content: space-between;
  flex-wrap: nowrap;
}

.search-row.second-row {
  justify-content: flex-start;
  margin-bottom: 0;
}

.form-group {
  margin-right: 12px;
  margin-bottom: 0;
}

.first-row .form-group {
  flex: 1;
  min-width: 0;
}

.form-group:last-child {
  margin-right: 0;
}

/* 让每个表单项内部更紧凑 */
.form-group :deep(.el-form-item) {
  margin-bottom: 0;
}

.form-group :deep(.el-form-item__label) {
  padding-right: 6px;
}

.form-group :deep(.el-form-item__content) {
  min-width: 150px;
}

.date-group {
  display: flex;
  margin-right: 20px;
}

.button-group {
  display: flex;
  align-items: flex-end;
}

.button-group .el-button {
  margin-right: 10px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 